﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DepSoft.Helpers.iTunes;
using DepSoft.Helpers.Console;
using System.ComponentModel;
using DepSoft.Helpers.iTunes.Elements;

namespace DepSoft.Console.iExporter
{
    class Program
    {
        #region Constants
        private const string OPTION_ITUNESLIBRARYFILE   = "libraryfile=";
        private const string OPTION_ITUNESPLAYLISTS     = "playlists=";
        private const string OPTION_ITUNESARTISTS       = "artists=";
        private const string OPTION_EXPORTLOCATION      = "exportlocation=";

        private const string OPTION_SUBFOLDERS          = "nosubfolders";
        private const string OPTION_EXPORT              = "noexport";
        #endregion

        #region Main entry
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                #region Initialize command line parser
                CommandLineParser commandLineParser = new CommandLineParser();
                commandLineParser.throwInvalidOptionsException = true;

                #region Command line option - iTunes Library file
                CommandLineParser.Option itunesLibrary = commandLineParser.AddStringParameter(string.Concat("-", OPTION_ITUNESLIBRARYFILE), "Location of the iTunes Library file", false);
                itunesLibrary.AddAlias(string.Concat("/", OPTION_ITUNESLIBRARYFILE));
                #endregion

                #region Command line option - iTunes Playlists
                CommandLineParser.Option iTunesPlayLists = commandLineParser.AddStringParameter(string.Concat("-", OPTION_ITUNESPLAYLISTS), "List of iTunes Playlists names to export ( or one name ) separated through #", false);
                iTunesPlayLists.AddAlias(string.Concat("/", OPTION_ITUNESPLAYLISTS));
                #endregion

                #region Command line option - iTunes Artists
                CommandLineParser.Option iTunesArtists = commandLineParser.AddStringParameter(string.Concat("-", OPTION_ITUNESARTISTS), "List of iTunes Album Artist names ( or one name ) separated through #", false);
                iTunesArtists.AddAlias(string.Concat("/", OPTION_ITUNESARTISTS));
                #endregion

                #region Command line option - Subfolders
                CommandLineParser.Option subfolders = commandLineParser.AddBoolSwitch(string.Concat("-", OPTION_SUBFOLDERS), "Do not create artist-album subfolders for the tracks being exported");
                subfolders.AddAlias(string.Concat("/", OPTION_SUBFOLDERS));
                #endregion

                #region Command line option - Exportlocation
                CommandLineParser.Option exportLocation = commandLineParser.AddStringParameter(string.Concat("-", OPTION_EXPORTLOCATION), "Location where the tracks will be exported to", true);
                exportLocation.AddAlias(string.Concat("/", OPTION_EXPORTLOCATION));
                #endregion

                #region Command line option - No file copy
                CommandLineParser.Option fileExport = commandLineParser.AddBoolSwitch(string.Concat("-", OPTION_EXPORT), "Do not export the actual files, only create m3u playlists");
                fileExport.AddAlias(string.Concat("/", OPTION_EXPORT));
                #endregion
                #endregion

                try
                {
                    commandLineParser.Parse(args);

                    if (!iTunesPlayLists.isMatched && !iTunesArtists.isMatched)
                        throw new CommandLineParser.MissingRequiredOptionException("No playlists or album artists arguments available!");

                    if(iTunesPlayLists.isMatched && iTunesArtists.isMatched)
                        throw new CommandLineParser.InvalidOptionsException("Playlists and Artists arguments can't be used together!");

                    iTunesLib itunesLib;

                    if (itunesLibrary.isMatched)
                        itunesLib = new iTunesLib(((string)itunesLibrary.Value).Replace("\"", string.Empty));
                    else
                        itunesLib = new iTunesLib();

                    System.Console.WriteLine("Parsing iTunes Library file...");
                    itunesLib.ParseiTunesLibrary();

                    BackgroundWorker backgroundWorker = new BackgroundWorker();
                    backgroundWorker.WorkerReportsProgress = true;

                    bool exportResult = false;

                    if (iTunesPlayLists.isMatched)
                    {
                        List<string> playlistsToExport = ((string)iTunesPlayLists.Value).Replace("\"", string.Empty).Split('#').ToList();
                        //List<iTunesPlaylist> selectediTunesPlayLists = (from iTunesPlayList in itunesLib.iTunesPlayLists
                        //                                                where playlistsToExport.Contains(iTunesPlayList.Name)
                        //                                                select iTunesPlayList).ToList();

                        System.Console.WriteLine("Exporting iTunes Playlists...");
                        List<iTunesPlaylist> selectediTunesPlayLists = (from iTunesPlayList in itunesLib.iTunesPlayLists
                                                                        where playlistsToExport.Exists(delegate(string argument)
                                                                        {
                                                                            return argument.Equals(iTunesPlayList.Name, StringComparison.OrdinalIgnoreCase);
                                                                        })
                                                                        select iTunesPlayList).ToList();

                        if (!fileExport.isMatched)
                            exportResult = itunesLib.ExportPlayLists(selectediTunesPlayLists, (string)exportLocation.Value, !subfolders.isMatched, ExportModeEnum.Normal, backgroundWorker);
                        else
                            exportResult = itunesLib.ExportPlayLists(selectediTunesPlayLists, (string)exportLocation.Value);
                    }

                    if (iTunesArtists.isMatched)
                    {
                        List<string> artistsToExport = ((string)iTunesArtists.Value).Replace("\"", string.Empty).Split('#').ToList();

                        System.Console.WriteLine("Exporting Album Artists...");
                        exportResult = itunesLib.ExportArtists(artistsToExport, (string)exportLocation.Value, !subfolders.isMatched, ExportModeEnum.Normal, backgroundWorker);
                    }

                    if(exportResult)
                        System.Console.WriteLine("Export completed!");
                    else
                        System.Console.WriteLine("Export failed!");
                }
                catch (Exception ex)
                {
                    if (ex is CommandLineParser.InvalidOptionsException || ex is CommandLineParser.MissingRequiredOptionException)
                    {
                        System.Console.WriteLine(ex.Message);
                        System.Console.WriteLine(commandLineParser.HelpMessage());
                    }
                    else
                        System.Console.WriteLine(ex.Message);
                        //throw;
                }
            }
        }
        #endregion
    }
}